package cn.thornbird.orgsync.helper.token;

import cn.thornbird.orgsync.helper.FeishuHelper;
import cn.thornbird.orgsync.model.certificate.FeishuCertificate;
import cn.thornbird.orgsync.model.feishu.Token;
import cn.thornbird.orgsync.util.JsonUtil;

import java.util.HashMap;
import java.util.Map;

public class FeishuToken extends AccessToken<FeishuCertificate> {

    public FeishuToken(String certificateText) {
        super(certificateText);
        Map<String, Object> map = JsonUtil.parseMap(certificateText);
        FeishuCertificate certificate = new FeishuCertificate();
        certificate.setAppId(map.get("appId").toString());
        certificate.setAppSecret(map.get("appSecret").toString());
        this.certificate = certificate;
    }

    @Override
    protected String acquireToken() {
        String token = INVALID_TOKEN_TEXT;
        FeishuHelper helper = new FeishuHelper();
        helper.initialize(null, certificateText);
        Map<String, Object> uriVariables = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("app_id", certificate.getAppId());
        params.put("app_secret", certificate.getAppSecret());
        long now = System.currentTimeMillis();
        Token result = helper.doPost(FeishuHelper.GET_TOKEN_PATH, params, null, Token.class);
        if (result != null && result.isSuccess()) {
            token = result.getTenantAccessToken() + "," + (now + result.getExpire() * 1000 + EXPIRATION_DELTA);
        }
        return token;
    }

}
